import style from './index.module.scss'
import HeaderView from '@/component/Header'
import TimeOut from '@/component/TimeOut'
import { useEffect, useState } from 'react'
import { AddCart, GetDetail, IsCollect } from '@/api/detail'
import { GetList } from '@/api/shopcart'
import { UserCollect } from '@/api/mine'
import { Image, Tag, Button, Tabs, Toast } from 'antd-mobile'
import { HeartOutline } from 'antd-mobile-icons'
import { productTuijian } from '@/type/detail'
import { useActivate } from 'react-activation'
import { getCookie } from '@/utils'
import { saveCollectNum } from '@/reduxToolkit/reducers/collectNum'
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { saveProductNum } from '@/reduxToolkit/reducers/productNum'

const Detail = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const [product, setProduct] = useState({
    id: 0,
    cover_url: '',
    title: '',
    price: 0,
    collects_count: 0,
    details: '',
    description: ''
  })
  const [collectFlag, setCollectFlag] = useState(0) // 收藏产品 0未收藏 1已收藏
  const [tuijian, setTuijian] = useState([]) // 图书推荐
  const [productID, setProductID] = useState(0) // 产品ID
  const [activeKey, setActiveKey] = useState('desc') // 选项卡当前激活项
  const [flag, setFlag] = useState(false) // 错误提示 

  // 数据初始化
  const init = async (id: number) => {
    const res = await GetDetail(id).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
    })

    try {
      if(res?.status === 200) {
        setProductID(id)
        setCollectFlag(res.data.goods.is_collect) // 产品收藏
        setProduct(res.data.goods) // 产品信息
        setTuijian(res.data.like_goods) // 推荐产品
      }  
    } catch (error) {
      console.log(error)  
    }
  }
  useEffect(() => {
    init(getCookie('id'))
  }, [])

  // 激活缓存
  useActivate(() => {
    if(getCookie('id') !== productID) {
      // 如果进入的是新产品页面, 那么先把上次的产品信息清空，不然会先看到上次的产品信息，然后在看到新的产品信息，体验不好
      setProduct({ id: 0,  cover_url: '', title: '', price: 0, collects_count: 0, details: '', description: ''})
      init(getCookie('id'))
      setActiveKey('desc')
    }
  })

  // 推荐产品
  const getContent = () => {
    return tuijian.map((item: productTuijian) => {
      return(
        <div className={style.item} key={item.id}>
          <Image src={item.cover_url}/>
          <p className={style.title}>{item.title}</p>
          <p className={style.description}>
            <span className={style.price}>￥{item.price}</span>
            <HeartOutline className={style.like} />
            <span>{item.collects_count}</span>
          </p>
        </div>
      )
    })
  }

  // 收藏产品
  const isCollect = async () => {
    const res = await IsCollect(product.id).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
      }
    })

    const res2 = await UserCollect()

    try {
      if(res?.status === 201) { // 收藏
        setCollectFlag(1)
        Toast.show({icon: 'success', content: '收藏成功', duration: 1500, maskClickable: false, afterClose: () => {
          dispatch(saveCollectNum(res2.data.data.length))
        }})
      }
      if(res?.status === 204) { // 为收藏
        setCollectFlag(0)
        Toast.show({icon: 'success', content: '取消成功', duration: 1500, maskClickable: false, afterClose: () => {
          dispatch(saveCollectNum(res2.data.data.length))
        }})
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 立即购买 或者 加入购物车
  const addBuy = async (type: string) => {
    const res = await AddCart({goods_id: product.id, num: 1}).catch(err => {})
    const res2= await GetList('include=goods')
    try {
      if(res?.status === 201 || res?.status === 204) {
        dispatch(saveProductNum(res2.data.data.length))
        if(type === 'add') {
          Toast.show({ icon: 'success', content: '添加成功', duration: 1500, maskClickable: true})
        } else {
          Toast.show({ icon: 'loading', content: '跳转中', duration: 1500, maskClickable: true, afterClose: () => {
            navigate('/shopcart')
          }})
        }
      }
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title='商品详情' backIcon={true} />

      {/* 产品信息 选项卡  product.cover_url !== '' 说明请求信息成功 那么才显示*/}
      { 
        product.cover_url !== '' 
        &&
        <>
         {/* 产品信息 */}
         <div className={style.productBox}>
            <Image src={product.cover_url}/>
            <div className={style.desc}>
              <p className={style.title}>{product.title}</p>
              <p className={style.ms}>{product.description}</p>

              <div className={style.tag}>
                <Tag color='#ff6430' fill='outline'>推荐</Tag>
                <Tag color='#ff6430' fill='outline'>新书</Tag>
              </div>

              <p className={style.price}>
                <span>￥</span>
                <span className={style.jg}>{product.price}</span>
                <span>.00</span>
              </p>

              <div className={style.btn}>
                <Button size='mini' color='warning' onClick={() => addBuy('add')}>加入购物车</Button>
                <Button size='mini' color='danger' onClick={() => addBuy('buy')}>立即购买</Button>
                <Button size='mini' color={collectFlag ? 'primary' : 'default'} onClick={() => isCollect()}>{collectFlag ? '已收藏' : '未收藏'}</Button>
              </div>  
            </div>
         </div>

         {/* tab选项卡 */}
         <Tabs activeKey={activeKey} onChange={(val: string) => setActiveKey(val)}>
        <Tabs.Tab title='概述' key='desc'>
          <div className={style.img} dangerouslySetInnerHTML={{__html: product.details}}></div>
        </Tabs.Tab>
        <Tabs.Tab title='热评' key='rating'>
          <p className={style.no}>暂无评价</p>
        </Tabs.Tab>
        <Tabs.Tab title='相关图书' key='about'>{getContent()}</Tabs.Tab>
         </Tabs>
        </> 
      }

      {/* 错误提示页面 */}
      {flag && <TimeOut/>}
    </>
  )
}

export default Detail